package com.android.nearshop.business.location;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/*********************************************************
 * @author : zhaohua
 * @version : 2012-9-5
 * @see : google api 管理器
 * @Copyright : copyrights reserved by personal 2007-2011
 **********************************************************/
public class GoogleAPIManger
{    
    private static final String url_ditu_geo  = "http://ditu.google.cn/maps/geo?output=json&language=zh&q=%s,%s";
    
    static Address reverseGeocode(double lat, double lon) 
        throws JSONException, ClientProtocolException, IOException
    {
        String url = String.format(url_ditu_geo, lat, lon);        
        String content = getContent(url);        
        return paresGeoAddress(content);
    }

    /**
     * @param url
     * @return
     */
    private static String getContent(String url)
    {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        get.setHeader("Accept-Encoding", "gzip");
        get.setHeader("Accept-Language", "zh");
        // 请求超时 
        client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
        // 读取超
        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
        
        try
        {
            HttpHost host = new HttpHost("ditu.google.com");
            HttpResponse rsp = client.execute(host ,get);
            HttpEntity entity = rsp.getEntity();
            
            InputStream instream = null; 
            Header contentEncoding = rsp.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) 
            {
                instream = new GZIPInputStream(entity.getContent());
            }else
            {
                instream = entity.getContent();
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(instream));
            
            StringBuffer sb = new StringBuffer();
            String result = br.readLine();
            
            while (result != null)
            {
                sb.append(result);
                result = br.readLine();
            }
            
            return sb.toString();
        }
        catch (ClientProtocolException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        
        return null;
    }
    
    /**
     * @param content
     * @return
     */
    private static Address paresGeoAddress(String content)
    {
        if(content == null) return null;
        
        JSONObject data = null;
        try
        {
            data = new JSONObject(content);
            JSONObject status = data.getJSONObject("Status");
            int code = status.getInt("code");
            
            if(200 == code)
            {
                // OK
                JSONArray results = (JSONArray) data.get("Placemark");
                JSONObject result = (JSONObject)results.get(0);             
                Address adr = new Address();
                if(!result.isNull("address"))
                {
                    adr.address = result.getString("address");
                }               
                JSONObject one = result.getJSONObject("AddressDetails").getJSONObject("Country").getJSONObject("AdministrativeArea");
                adr.province = one.getString("AdministrativeAreaName");
                JSONObject one2 = one.getJSONObject("Locality");
                adr.city = one2.getString("LocalityName");
                JSONObject one3 = null;
                try{
                    one3 = one2.getJSONObject("DependentLocality");
                    adr.county = one3.getString("DependentLocalityName");
                }catch (Exception e) 
                {
                    e.printStackTrace();
                }
                try{
                    if(one3 != null) adr.line = (String)one3.getJSONArray("AddressLine").get(0);
                }catch (Exception e) 
                {
                    e.printStackTrace();
                }
                try{
                    if(one3 != null) adr.route = one3.getJSONObject("Thoroughfare").getString("ThoroughfareName");
                }catch (Exception e) 
                {
                    e.printStackTrace();
                }
                return adr;
            }else
            {
                // Fail
                return null;
            }
        }
        catch (JSONException e)
        {
            e.printStackTrace();
            
        }catch(Exception e)
        {
            e.printStackTrace();
        }
        
        return null;
    }
}
